package com.x.utils.http;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

/**
 * <p>
 * Title:IPUtil
 * </p>
 * <p>
 * Description:获取IP工具类
 * </p>
 * 
 * @Author Chenkangming @Date 2013-9-5
 * @version 1.0
 */
public class IPUtil {

	private static Logger log = LoggerFactory.getLogger(IPUtil.class);

	/**
	 * 获取网络中真实的IP地址
	 * 
	 * @param request
	 * @return ip
	 */
	public static String getIPFromRequest(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] arrIp = ip.split(",");
		if (arrIp.length > 1) {
			ip = arrIp[1];
		}
		return ip.trim();
	}

	/**
	 * 百度IP归属地接口
	 * 
	 * @param ip
	 *            IP
	 * @param url
	 *            url请求地址
	 * @param apikey
	 *            apikey
	 * @return {ip,province,city,isp}
	 */
	public static JSONObject baiduForIP(String ip, String url, String apikey) {
		JSONObject info = new JSONObject();
		// 百度
		try {
			HttpRequest httpRequest = HttpRequest.get(url + ip);
			httpRequest.header("apikey", apikey);
			HttpResponse response = httpRequest.send();
			String result = response.bodyText();
			log.debug("ipinfo >> " + result);
			JSONObject json = JSONObject.parseObject(result);
			if (json.getInteger("errNum") != 0) {
				log.error("百度解析ip地址异常{}", json.toJSONString());
				return null;
			} else {
				JSONObject retData = json.getJSONObject("retData");
				info.put("ip", ip);
				info.put("province", retData.get("province"));
				info.put("city", retData.get("city"));
				String sp = retData.getString("carrier");
				if (sp.contains("移动")) {
					info.put("isp", "中国移动");
				} else if (sp.contains("电信")) {
					info.put("isp", "中国电信");
				} else if (sp.contains("联通")) {
					info.put("isp", "中国联通");
				} else {
					info.put("isp", sp);
				}
				return info;
			}
		} catch (Exception e) {
			log.error("百度IP地址请求异常{}", e);
		}
		return null;
	}

	// 将127.0.0.1形式的IP地址转换成十进制整数，这里没有进行任何错误处理
	public static long ipToLong(String strIp) {
		long[] ip = new long[4];
		// 先找到IP地址字符串中.的位置
		int position1 = strIp.indexOf(".");
		int position2 = strIp.indexOf(".", position1 + 1);
		int position3 = strIp.indexOf(".", position2 + 1);
		// 将每个.之间的字符串转换成整型
		ip[0] = Long.parseLong(strIp.substring(0, position1));
		ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));
		ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));
		ip[3] = Long.parseLong(strIp.substring(position3 + 1));
		return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
	}

	// 将十进制整数形式转换成127.0.0.1形式的ip地址
	public static String longToIP(long longIp) {
		StringBuffer sb = new StringBuffer("");
		// 直接右移24位
		sb.append(String.valueOf((longIp >>> 24)));
		sb.append(".");
		// 将高8位置0，然后右移16位
		sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));
		sb.append(".");
		// 将高16位置0，然后右移8位
		sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));
		sb.append(".");
		// 将高24位置0
		sb.append(String.valueOf((longIp & 0x000000FF)));
		return sb.toString();
	}

}
